package com.kancy.delay.queue.redis.handler;

import com.kancy.delay.queue.redis.properties.DelayQueueProperties;
import com.kancy.delay.queue.redis.properties.TopicProperties;
import com.kancy.delay.queue.redis.message.DelayMessage;
import com.kancy.delay.queue.redis.service.DelayQueueClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * ReenterDelayQueueExceptionHandler
 * <p>
 *
 * @author: kancy
 * @date: 2020/3/5 21:25
 **/
public class ReenterDelayQueueExceptionHandler implements DelayQueueExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(ReenterDelayQueueExceptionHandler.class);

    private final DelayQueueClient delayQueueClient;
    private final DelayQueueProperties delayQueueProperties;

    public ReenterDelayQueueExceptionHandler(DelayQueueClient delayQueueClient, DelayQueueProperties delayQueueProperties) {
        this.delayQueueClient = delayQueueClient;
        this.delayQueueProperties = delayQueueProperties;
    }

    /**
     * 消费异常
     *
     * @param handler
     * @param delayMessage
     * @param exception
     */
    @Override
    public void onProcessMessageException(DelayQueueMessageHandler handler, DelayMessage delayMessage, Exception exception) {
        TopicProperties topicProperties = delayQueueProperties.getTopics().get(delayMessage.getTopic());
        Integer maxRetry = topicProperties.getMaxRetry();
        Integer currentRetry = delayMessage.getRetry();
        if (currentRetry < maxRetry){
            delayMessage.setDelay(topicProperties.getRetryInterval());
            delayMessage.setRetry(++currentRetry);
            delayQueueClient.sendMessage(delayMessage);
            log.info("Retry [{}] reenter topic [{}] delay message [{}] succeeded.",
                    currentRetry, delayMessage.getTopic(), delayMessage.getId());
        }else {
            log.info("Retry [{}] processing topic [{}] delay message [{}] failed.",
                    currentRetry, delayMessage.getTopic(), delayMessage.getId());
        }
    }
}
